package process0.visitor;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import process0.ast.Action;
import process0.ast.Process;
import process0.ast.States;
import process0.ast.Timeline;
import process0.ast.Workflow;

public class VisitorImpl implements Visitor {
	private String output;

	public void visit(Process node) {
		output = ";--------";
		output = output + "\n; process: " + node.getId();
		output = output + "\n;--------";
		
		if (node.getTimeline() != null) {
			output = output + "\n\n" + "[timeline]";
			node.getTimeline().accept(this);
		}
		
		for (Workflow workflow : node.getWorkflows()) {
			workflow.accept(this);
		}

		writeToFile(node.getId(), output);
		System.out.println(output);
	}

	public void visit(Timeline node) {
		output = output  + "\n" + node.getId();
		
		for (Timeline timeline : node.getTimeline()) {
			timeline.setParentId(node.getId());
			timeline.accept(this);
		}
	}
	
	
	public void visit(Workflow node) {
		output = output + "\n" + "\n[ticket-workflow]"+ "\n;" + node.getId();
		for (Action action : node.getActions()) {
			action.accept(this);
		}
	}

	public void visit(Action node) {
		for (States state : node.getStates()) {
			state.accept(this);
		}
	}

	public void visit(States node) {
		String out = node.getActionId() + " = ";
		for (String string : node.getInitialStates()) {
			out += string + ", ";
		}
		out = out.substring(0, out.length() - 2);
		out = out + " -> " + node.getEndState();
		output = output + "\n" + out;
	}

	
	private void writeToFile(String filename, String output){
		try {
			PrintWriter out = new PrintWriter(new FileWriter(filename+".ini"));
			out.println(output);
			out.close();
			System.out.println("file: "+ filename+".ini" + " created successfully");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
